import hashlib
from xml.etree import ElementTree
from utils.wechat.receive import (
    EventMessage,
    ImageMessage,
    TextMessage,
    VoiceMessage,
    BaseMessage
)


def check_wx_signature(token, timestamp, nonce, signature):
    tmp_ls = [token, timestamp, nonce]
    tmp_ls.sort()
    temp = ''.join(tmp_ls)
    sha1 = hashlib.sha1(temp.encode('utf-8'))
    hashcode = sha1.hexdigest()
    return hashcode == signature


def parse_wx_msg(xml):
    xml_data = ElementTree.fromstring(xml)
    msg_type = xml_data.find('MsgType').text
    if msg_type == 'text':
        return TextMessage(xml_data)
    elif msg_type == 'image':
        return ImageMessage(xml_data)
    elif msg_type == 'voice':
        return VoiceMessage(xml_data)
    elif msg_type == 'event':
        return EventMessage(xml_data)
    else:
        return BaseMessage(xml_data)
